package com.chunhe.sojourn.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.chunhe.sojourn.common.controller.BaseController;
import com.chunhe.sojourn.common.domain.QueryRequest;
import com.chunhe.sojourn.common.domain.Result;
import com.chunhe.sojourn.common.exception.FebsException;
import com.chunhe.sojourn.system.domain.Dict;
import com.chunhe.sojourn.system.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

@Slf4j
@Validated
@RestController
@RequestMapping("/backend/dict")
public class DictController extends BaseController {

    private String message;

    @Resource
    private DictService dictService;

    @GetMapping
    public Map<String, Object> DictList(QueryRequest request, Dict dict) {
        return getDataTable(this.dictService.findDicts(request, dict));
    }

    @GetMapping("/list")
    public Result<List<Dict>> getList(String category) {
        return Result.OK(this.dictService.list(new LambdaQueryWrapper<Dict>().eq(Dict::getCategory, category)));
    }


    @PostMapping
    public Result addDict(@Valid Dict dict) throws FebsException {
        try {
            this.dictService.createDict(dict);
            return Result.OK();
        } catch (Exception e) {
            message = "新增字典成功";
            log.error(message, e);
            return Result.error(message);
        }
    }

    @DeleteMapping("/{dictIds}")
    public Result deleteDicts(@NotBlank(message = "{required}") @PathVariable String dictIds) throws FebsException {
        try {
            String[] ids = dictIds.split(StringPool.COMMA);
            this.dictService.deleteDicts(ids);
            return Result.OK();
        } catch (Exception e) {
            message = "删除字典成功";
            log.error(message, e);
            return Result.error(message);
        }
    }

    @PutMapping
    public Result updateDict(@Valid Dict dict) throws FebsException {
        try {
            this.dictService.updateDict(dict);
            return Result.OK();
        } catch (Exception e) {
            message = "修改字典成功";
            log.error(message, e);
            return Result.error(message);
        }
    }
}
